<?php

namespace app\api\controller;

use app\api\model\System as SystemModel;
use app\api\model\User as UserModel;
use app\BaseController;
use app\lib\tool\Str;
use think\facade\Cache;

class User extends BaseController
{
    /* 自动加载 */
    public function initialize()
    {
        $this->uid = $this->request->uid;
    }

    /* 检测token合法性 */
    public function checkToken()
    {
        if (!$this->request->auth) {
            return show(config('status.auth'), 'Authorization Failed');
        } else {
            return show(config('status.success'), 'Token合法');
        }
    }

    /* 授权登录[H5] */
    public function login()
    {
        // 1.通过code获取access_token
        $cid = input('cid', '');
        $code = input('code', '');
        $one = SystemModel::field('appid, appsecret')->where('id', $cid)->find();
        $appid = $one['appid'];
        $appsecret = $one['appsecret'];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $result = curl($url);
        if (isset($result['errcode']) && $result['errcode'] == 40029) {
            return show($result['errcode'], '微信授权验证code错误');
        }

        // 2.获取用户信息
        $token = $result['access_token'];
        $openid = $result['openid'];
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $token . '&openid=' . $openid . '&lang=zh_CN';
        $userinfo = curl($url);
        if (isset($userinfo)) {
            $wx = $userinfo['openid'];
            $wxname = $userinfo['nickname'];
            $wximage = $userinfo['headimgurl'];
            $time = time();

            $user = UserModel::where('wx', $wx)->find();
            if (!$user) {
                // 注册用户
                $user = UserModel::create([
                    'wx' => $wx,
                    'wxname' => $wxname,
                    'wximage' => $wximage,
                    'time' => $time
                ]);
            }

            // 获取token
            $token = Str::getToken();
            $redisData = [
                'id' => intval($user['id'])
            ];
            Cache::set(config('cache.redis.prefix') . $token, $redisData, config('cache.redis.timeout'));
            $data = ['token' => $token];
            return show(config('status.success'), '登录成功', $data);
        } else {
            return show(config('status.error_login_wx'), '登录失败');
        }
    }

    /* 获取 */
    public function getInfo()
    {
        if (!$this->request->auth) return show(config('status.auth'), 'Authorization Failed');
        $data = UserModel::where('id', $this->uid)->find();
        return show(config('status.success'), '获取用户信息', $data);
    }

    /* 设置 */
    public function setInfo()
    {
        if (!$this->request->auth) return show(config('status.auth'), 'Authorization Failed');
        $field = input('field', '');
        $value = input('value', '');
        UserModel::update([
            'id' => $this->uid,
            $field => $value
        ]);
        return show(config('status.success'), '设置用户信息');
    }
}
